package org.jks.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {
	public static SimpleDateFormat ymd=new SimpleDateFormat("yyyy-MM-dd");
	public static SimpleDateFormat ymdhms=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static SimpleDateFormat ymdhms_t = new SimpleDateFormat("yyyyMMddHHmmss");
	public static Date toDate(String date, String format) {
		if(date == null || date.length() == 0 || format == null || format.length() == 0){
			return null;
		}
		
		try {
			if(format.equals("yyyy-MM-dd")){
				return ymd.parse(date);
			}
			else if(format.equals("yyyy-MM-dd HH:mm:ss")){
				return ymdhms.parse(date);
			}
			else if(format.equals("yyyyMMddHHmmss")){
				return ymdhms_t.parse(date);
			}
			else{
				SimpleDateFormat sdf=new SimpleDateFormat(format);
				return sdf.parse(date);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String toString(Date date, String format){
		if(date == null || format == null || format.length() == 0){
			return "";
		}
		if(format.equals("yyyy-MM-dd")){
			return ymd.format(date);
		}
		else if(format.equals("yyyy-MM-dd HH:mm:ss")){
			return ymdhms.format(date);
		}
		else if(format.equals("yyyyMMddHHmmss")){
			return ymdhms_t.format(date);
		}
		else{
			SimpleDateFormat sdf=new SimpleDateFormat(format);
			return sdf.format(date);
		}
	}
	
	public static String toCron(java.util.Date  date){
	    String dateFormat="ss mm HH dd MM ? yyyy";
	    return toString(date, dateFormat);
	  }
}
